<template>
  <div class="users">
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加搜索 -->
      <el-row :gutter="30">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserInfo"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" plain @click="isAddUser=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表展示 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserInfo(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="open2(scope.row)"
            ></el-button>
            <el-tooltip class="item" effect="dark" content="设置" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      @close="clearFrom"
      :visible.sync="isAddUser"
      width="50%"
    >
      <!-- 表单 -->
      <!-- 表单 -->
      <span slot="footer" class="dialog-footer">
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="isAddUser = false">取 消</el-button>
        <el-button type="primary" @click="AddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      @close="clearEditFrom"
      :visible.sync="isEditUser"
      width="60%"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditUser = false">取 消</el-button>
        <el-button type="primary" @click="EditUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除提示框 -->
  </div>
</template>
<script>
  export default {
    name: 'user',
    data() {
      // 自定义校验 规则
      var checkMobile = (rule, value, cb) => {
        const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        setTimeout(() => {
          if (reg.test(value)) {
            return cb()
          } else {
            cb(new Error('手机号不符合规则'))
          }
        }, 100)
      }
      var checkEmail = (rule, value, cb) => {
        const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (reg.test(value)) {
          return cb()
        } else {
          cb(new Error('邮箱不符合规则'))
        }
      }

      return {
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 2
        },
        userList: [],
        total: 0,
        isAddUser: false,
        isEditUser: false,
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 保存id 查询道到的用户信息
        editForm: {},

        addFormRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur' }
          ]
        },
        editFormRules: {
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.getUserInfo()
    },
    methods: {
      async getUserInfo() {
        console.log('this.queryInfo :>> ', this.queryInfo)
        const { data } = await this.$http.get('users', { params: this.queryInfo })
        // console.log('data :>> ', data.data.users)
        if (data.meta.status !== 200) return this.$message.error('获取失败')
        this.userList = data.data.users
        this.total = data.data.total
      },
      clearFrom() {
        console.log('this.$refs.addFormRef :>> ', this.$refs.addFormRef)
        this.$refs.addFormRef.resetFields()
      },
      handleSizeChange(val) {
        this.queryInfo.pagesize = val
        this.getUserInfo()
      },
      handleCurrentChange(val) {
        this.queryInfo.pagenum = val
        this.getUserInfo()
      },
      async userStateChanged(val) {
        console.log('val :>> ', val.mg_state)
        const { data } = await this.$http.put(
          `users/${val.id}/state/${val.mg_state}`
        )
        if (data.meta.status !== 200) {
          val.mg_state = !val.mg_state
          return this.$message.error('更新数据失败')
        }
        this.$message.success('更新数据成功')
      },
      AddUser() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          // 发起添加请求
          const { data } = await this.$http.post('users', this.addForm)
          console.log('data :>> ', data)
          if (data.meta.status !== 201) return this.$message.error('添加失败')
          this.$message.success('添加成功')
          this.isAddUser = false
          this.getUserInfo()
        })
      },
      async editUserInfo(id) {
        const { data: res } = await this.$http.get(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('查询失败')
        // console.log(res.data)
        this.editForm = res.data
        console.log('this.editForm :>> ', this.editForm)
        //显示弹框
        this.isEditUser = true
      },
      clearEditFrom() {
        this.$refs.editFormRef.resetFields()
      },
      // 预验证
      EditUserInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          const { data } = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })

          if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
          this.isEditUser = false
          this.getUserInfo()
          this.$message.success(data.meta.msg)
        })
      },
      // 删除提示框
      async open2(info) {
        const confirm = await this.$confirm(
          `此操作将永久删除 ${info.username}  的所有信息, 是否继续?`,
          '删除此用户',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(err => err)
        if (confirm == 'cancel') {
          this.$message.success('取消删除')
        } else if (confirm == 'confirm') {
          const { data } = await this.$http.delete('users/' + info.id)
          if (data.meta.status == 200) this.$message.success('删除操作成功')
          this.getUserInfo()
        }
      }
    }
  }
</script>